package com.example.demo.controller;

import com.example.demo.dto.AiRequest;
import com.example.demo.dto.AiResponse;
import com.example.demo.service.SmartGeneratorService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * AI功能控制器
 * 提供营销文案生成、代码生成、智能问答、聊天对话等API
 * 
 * @author Spring AI Demo
 */
@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AiController {

    private static final Logger logger = LoggerFactory.getLogger(AiController.class);

    private final SmartGeneratorService smartGeneratorService;

    public AiController(SmartGeneratorService smartGeneratorService) {
        this.smartGeneratorService = smartGeneratorService;
    }

    /**
     * 营销文案生成API
     * 
     * @param request 请求参数
     * @return 生成的营销文案
     */
    @PostMapping("/marketing")
    public ResponseEntity<AiResponse> generateMarketingContent(@Valid @RequestBody AiRequest request) {
        logger.info("收到营销文案生成请求：{}", request.getContent());
        
        try {
            AiResponse response = smartGeneratorService.generateMarketingContent(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("营销文案生成API调用失败", e);
            return ResponseEntity.internalServerError()
                    .body(AiResponse.error("服务器内部错误：" + e.getMessage()));
        }
    }

    /**
     * 代码生成API
     * 
     * @param request 请求参数
     * @return 生成的代码
     */
    @PostMapping("/code")
    public ResponseEntity<AiResponse> generateCode(@Valid @RequestBody AiRequest request) {
        logger.info("收到代码生成请求：{}", request.getContent());
        
        try {
            AiResponse response = smartGeneratorService.generateCode(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("代码生成API调用失败", e);
            return ResponseEntity.internalServerError()
                    .body(AiResponse.error("服务器内部错误：" + e.getMessage()));
        }
    }

    /**
     * 智能问答API
     * 
     * @param request 请求参数
     * @return 问题的答案
     */
    @PostMapping("/qa")
    public ResponseEntity<AiResponse> answerQuestion(@Valid @RequestBody AiRequest request) {
        logger.info("收到智能问答请求：{}", request.getContent());
        
        try {
            AiResponse response = smartGeneratorService.answerQuestion(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("智能问答API调用失败", e);
            return ResponseEntity.internalServerError()
                    .body(AiResponse.error("服务器内部错误：" + e.getMessage()));
        }
    }

    /**
     * 聊天对话API
     * 
     * @param request 请求参数
     * @return 聊天回复
     */
    @PostMapping("/chat")
    public ResponseEntity<AiResponse> chat(@Valid @RequestBody AiRequest request) {
        logger.info("收到聊天对话请求：{}", request.getContent());
        
        try {
            AiResponse response = smartGeneratorService.chat(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("聊天对话API调用失败", e);
            return ResponseEntity.internalServerError()
                    .body(AiResponse.error("服务器内部错误：" + e.getMessage()));
        }
    }

    /**
     * 简单文本生成API（GET方式，用于快速测试）
     * 
     * @param message 用户消息
     * @param temperature 温度参数（可选）
     * @return 生成的回复
     */
    @GetMapping("/simple")
    public ResponseEntity<AiResponse> simpleChat(
            @RequestParam String message,
            @RequestParam(required = false) Double temperature) {
        logger.info("收到简单聊天请求：{}", message);
        
        try {
            AiRequest request = new AiRequest(message, temperature);
            AiResponse response = smartGeneratorService.chat(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("简单聊天API调用失败", e);
            return ResponseEntity.internalServerError()
                    .body(AiResponse.error("服务器内部错误：" + e.getMessage()));
        }
    }

    /**
     * 健康检查API
     * 
     * @return 服务状态
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("AI服务运行正常 ✅");
    }

    /**
     * 获取支持的功能列表
     * 
     * @return 功能列表
     */
    @GetMapping("/features")
    public ResponseEntity<Object> getFeatures() {
        var features = new Object() {
            public final String[] supportedFeatures = {
                "营销文案生成 (POST /api/ai/marketing)",
                "代码生成 (POST /api/ai/code)", 
                "智能问答 (POST /api/ai/qa)",
                "聊天对话 (POST /api/ai/chat)",
                "简单对话 (GET /api/ai/simple?message=你好)",
                "流式聊天 (GET /api/stream/chat?message=你好)"
            };
            public final String model = "deepseek-chat";
            public final String version = "1.0.0";
            public final String description = "Spring AI + DeepSeek 智能文本生成服务";
        };
        
        return ResponseEntity.ok(features);
    }
} 